package com.huafeng.context;

import com.huafeng.listener.Listener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 花风
 * @date 2023/4/5 22:26
 * @Description 监听器上下文
 */
@Component
public class ListenerContext implements BeanFactoryPostProcessor {
    private final static Map<String, Listener> map = new HashMap<>();

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //在容器中获取标有@Answer注解的
        Map<String, Object> beans = configurableListableBeanFactory.getBeansWithAnnotation(com.huafeng.annotations.Listener.class);
        Optional.ofNullable(beans).orElse(beans)
                .forEach((name,bean) -> {
                    Class<?> aClass = bean.getClass();
                    com.huafeng.annotations.Listener listener = aClass.getAnnotation(com.huafeng.annotations.Listener.class);
                    map.putIfAbsent(listener.type(), (Listener) bean);
                });
    }

    public static Listener get(String type){
        Listener listener = map.get(type);
        if (listener == null){
            throw new NullPointerException("can not find listener");
        }
        return listener;
    }
}
